#
# Copyright (C) 2023, Inria
# GRAPHDECO research group, https://team.inria.fr/graphdeco
# All rights reserved.
#
# This software is free for non-commercial, research and evaluation use 
# under the terms of the LICENSE.md file.
#
# For inquiries contact  george.drettakis@inria.fr
#

import torch
from scene import Scene
import os
from tqdm import tqdm
from random import randint
import numpy as np
from tqdm import tqdm
from os import makedirs
from gaussian_renderer import render
import torchvision
from utils.general_utils import safe_state
from argparse import ArgumentParser
from arguments import ModelParams, PipelineParams, get_combined_args
from gaussian_renderer import GaussianModel
from utils.mlp_utils import EmbeddingExtractor

mse_loss = lambda x, y: torch.sqrt((x - y) ** 2).mean()

def training(dataset : ModelParams, args):
    gaussians = GaussianModel(dataset)
    scene = Scene(dataset, gaussians, load_iteration=args.iteration, shuffle=False)
    extractor = EmbeddingExtractor(hidden_dim=128, out_dim=dataset.appearance_dim, n_layers=4).cuda()
    
    total_iterations = args.total_iterations
    learning_rate = args.learning_rate
    alpha = args.learning_rate_alpha
    optimizer = torch.optim.Adam(extractor.parameters(), lr=args.learning_rate)
    
    viewpoint_stack = None
    for cur_iter in tqdm(range(total_iterations), desc='training extractor...'):
        if not viewpoint_stack:
            viewpoint_stack = scene.getTrainCameras().copy()
        idx = randint(0, len(viewpoint_stack)-1)
        image = viewpoint_stack.pop(idx).original_image.cuda()[None]
        idx_emb = torch.full((1), idx, dtype=torch.long, device='cuda')
        gt_embedding = gaussians.embedding_appearance(idx_emb).detach().clone()        
        ge_embedding = extractor(image)
        loss = mse_loss(gt_embedding, ge_embedding)
        loss.backward()
        
        if cur_iter % 1000 == 0:
            print(f"LOSS={loss.item():.6f}, LR={optimizer.param_groups[0]['lr']:.6f}")
                
        
        progress = cur_iter / total_iterations
        learning_factor = (np.cos(np.pi * progress) + 1.0) * 0.5 * (1 - alpha) + alpha
        for g in optimizer.param_groups:
            g['lr'] = learning_rate * learning_factor
    


if __name__ == "__main__":
    # Set up command line argument parser
    parser = ArgumentParser(description="Testing script parameters")
    model = ModelParams(parser, sentinel=True)
    pipeline = PipelineParams(parser)
    parser.add_argument("--iteration", default=-1, type=int)
    parser.add_argument("--learning_rate", default=0.0005, type=float)
    parser.add_argument("--learning_rate_alpha", default=0.05, type=float)
    parser.add_argument("--total_iterations", default=200000, type=int)
    parser.add_argument("--quiet", action="store_true")
    args = get_combined_args(parser)
    print("Rendering " + args.model_path)

    # Initialize system state (RNG)
    safe_state(args.quiet)

    training(model.extract(args), args)